<?php

namespace common\helpers;

/**
 * 实用辅助类
 *
 * @author Dean
 */
class UtilityHelper
{

    /**
     * 生成指定长度的字符串，默认值从0-9数字中生成
     * 如果includeLetter为true，则包括52个大小写字母
     * 
     * @param int $length 随机字符串的长度
     * @param boolean $includeLetter 是否包含字母
     * @param boolean $includeUpperLetter 是否包含大写字母
     * @return string
     */
    public static function randomString($length = 6, $includeLetter = false, $includeUpperLetter = false)
    {
        $numMap = [1, 2, 3, 4, 0, 5, 6, 7, 8, 9];
        $letterMap = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
        $upperLetter = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
        if ($includeLetter == true) {
            $map = array_merge($numMap, $letterMap);
        } else {
            $map = $numMap;
        }
        if ($includeUpperLetter == true) {
            $map = array_merge($map, $upperLetter);
        }
        $rand = array_rand($map, $length);
        $returnString = '';
        foreach ($rand as $mapKey) {
            $returnString .= $map[$mapKey];
        }
        return $returnString;
    }

    /**
     * 返回当前使用者的IP地址，如果没有IP，则返回空
     */
    public static function getIp()
    {
        if (!isset(\Yii::$app->request)) {
            return null;
        }
        return \Yii::$app->request->getUserIP();
    }

    /**
     * 
     * @return int 返回当前登录的用户ID
     */
    public static function getUserId()
    {
        return 0;
    }

    /**
     * 根据生日获取年龄
     * @param date $birthday
     * @return integer
     */
    public static function getAgeByBirthday($birthday)
    {
        $birthTimestamp = strtotime($birthday);
        $current = time();
        $age = date('Y', $current) - date('Y', $birthTimestamp) - 1;
        if (date('m', $current) == date('m', $birthTimestamp)) {
            if (date('d', $current) > date('d', $birthTimestamp)) {
                $age++;
            }
        } elseif (date('m', $current) > date('m', $birthTimestamp)) {
            $age++;
        }
        return $age;
    }
    
    /**
     * 拼接上静态服务器域名，返回完整的URL绝对路径
     * @param string $path
     * @return string
     */
    public static function createStaticUrl($path)
    {
        if(empty($path)){
            return '';
        }
        return \Yii::$app->params['staticDomain'] . $path;
    }
    
    /**
     * 生成视频地址
     * @param type $path
     * @return type
     */
    public static function createVideoUrl($path)
    {
        if(empty($path)){
            return '';
        }
        return \Yii::$app->params['staticDomain'] . $path;
    }

}
